module.exports = (EdtApi) => {
    "use strict";
    let chatId = "", count = 0, badges;
    function isGroup() {
        let el = document.querySelector("button[style='position: relative; display: flex; flex-direction: row; flex-grow: 0; flex-shrink: 1; overflow: hidden; align-items: stretch; justify-content: flex-start; app-region: no-drag; background-color: transparent; border-color: transparent; text-align: left; border-width: 0px; cursor: pointer; padding: 0px; border-style: solid;']");
        if (!el) return false;
        return !isNaN(parseFloat(el.getAttribute('title')));
    }
    async function getChatId(times = 0) {
        let headerEl = document.querySelector('button[role="button"][title][aria-label]>div[role="none"]>div[dir="auto"],div.app-container div.noFocusOutline div.css-1dbjc4n.r-1p0dtai.r-18u37iz.r-1d2f490.r-u8s1d.r-zchlnj.r-ipm5af div.css-901oao.css-cens5h');
        let id = headerEl?.textContent || '';
        if (id && id != chatId) return id;
        await EdtApi.sleep(50);
        if (times > 10) return id;
        times++;
        return getChatId(times);
    }
    return {
        config: {
            friendList: 'div[role="list"]>div.rxCustomScroll.rxCustomScrollV,div[role="group"]>div.rxCustomScroll.rxCustomScrollV',
            chat: 'div.app-container div.noFocusOutline div.css-1dbjc4n.r-1p0dtai.r-18u37iz.r-1d2f490.r-u8s1d.r-zchlnj.r-ipm5af',
            input: "div.DraftEditor-root div.DraftEditor-editorContainer div.public-DraftEditor-content",
            msgBox: 'div.app-container div.noFocusOutline div.css-1dbjc4n.r-1p0dtai.r-18u37iz.r-1d2f490.r-u8s1d.r-zchlnj.r-ipm5af div.rxCustomScroll.rxCustomScrollV div.scrollViewport.scrollViewportV,div.app-container div.noFocusOutline div.css-1dbjc4n.r-1p0dtai.r-18u37iz.r-1d2f490.r-u8s1d.r-zchlnj.r-ipm5af div.css-1dbjc4n.r-1awozwy.r-13awgt0.r-1777fci.r-15bsvpr',
            inMsg: 'div[role="region"]>div>div[style*="flex-start"] div[style*="0px 10px 10px"]>div[style*="stretch"]:not(.trans-inited,.trans-info),div[role="region"]>div>div[style*="flex-start"] div[style*="0px 10px 10px 0px"]>div[style*="stretch"]:not(.trans-inited,.trans-info)',
            outMsg: 'div[role="region"]>div>div[style*="flex-end"] div[style*="10px 10px 0px"]>div[style*="stretch"]:not(.trans-inited),div[role="region"]>div>div[style*="flex-end"] div[style*="10px 0px 0px 10px"]>div[style*="stretch"]:not(.trans-inited,.trans-info)',
            sendBtn: "button[title='发送消息'],button[title='Send message'],button[title='메시지 보내기'],button[title='メッセージを送信'],button[title='傳送訊息']",
            setting: 'div.DraftEditor-editorContainer',
            tips: {
                in: 'div.app-container div.noFocusOutline div.css-1dbjc4n.r-1p0dtai.r-18u37iz.r-1d2f490.r-u8s1d.r-zchlnj.r-ipm5af div[style="position: relative; display: flex; flex-direction: column; flex-grow: 1; flex-shrink: 1; overflow: hidden; align-items: stretch; justify-content: center;"]',
                out: 'div.app-container div.noFocusOutline div.css-1dbjc4n.r-1p0dtai.r-18u37iz.r-1d2f490.r-u8s1d.r-zchlnj.r-ipm5af div[style="position: relative; display: flex; flex-direction: column; flex-grow: 1; flex-shrink: 1; overflow: hidden; align-items: stretch; background-color: rgb(255, 255, 255);"]',
            },
            crm: {
                // listener: '#LeftColumn-main',
                top: '#detail-header>div.css-175oi2r',
                left: ""
            },
            extra: {//其他会触发对话框变动的情况处理
                selector: "button[title='发送音频消息'],button[title='Send audio message'],button[title='음성 메시지 보내기'],button[title='音声メッセージを送信'],button[title='傳送語音留言']",
                level: 10,
                delay: 600
            },
            autoCount: 20
        },
        inputMsg(inputEl, msg) {//必须
            return new Promise((resolve) => {
                inputEl?.focus();
                document.execCommand("selectAll");
                EdtApi.sleep(20).then(() => {
                    navigator.clipboard.writeText(msg).then(() => {
                        document.execCommand("paste");
                        resolve(true);
                    }).catch(() => {
                        resolve(false);
                    });
                });
            });
        },
        getUnread() {
            count = 0;
            badges = document.querySelectorAll('div[role="listitem"] div.css-1dbjc4n.r-1awozwy>div.css-901oao.r-jwli3a');
            badges?.forEach(badge => {
                count += EdtApi.safeParseInt(badge.textContent || "0");
            });
            return count;
        },
        getMessageList() {//获取消息列表
            return {
                in: document.querySelectorAll(this.config.inMsg),
                out: document.querySelectorAll(this.config.outMsg),
            };
        },
        getChatInfo() {
            return new Promise((resolve) => {
                EdtApi.sleep(300).then(async () => {
                    chatId = await getChatId();
                    console.log(document.querySelectorAll(this.config.tips.in));
                    resolve({ id: chatId, isGroup: isGroup() })
                }).catch(() => { });
            });
        },
        getText(msgBox) {
            if (!msgBox) return "";
            try {
                let msgEl = msgBox.querySelector('div[dir="auto"][style*="text"][style*="pre-wrap"][style*="break-word"]');
                return msgEl?.textContent || msgBox.textContent || "";
            } catch (error) {
                console.error(error);
            }
            return "";
        },
        getIptMsg(inputEl) {
            if (!inputEl) return "";
            let value = ''
            try {
                let childrens = inputEl.querySelectorAll('.public-DraftStyleDefault-block.public-DraftStyleDefault-ltr>span')
                childrens?.forEach(item => {
                    value += item.textContent;
                })
            } catch (error) {
                console.error(error);
            }
            return value;
        },
        getPlaceholderEl(chat = document) {
            let el = chat.querySelector('.DraftEditor-root')?.parentNode?.parentNode?.querySelector('div[aria-hidden="true"]');
            if (el) el.style.paddingLeft = "30px";
            return el;
        },
        // inputMsg(inputEl, msg) {//必须
        //     return new Promise((resolve) => {
        //         inputEl?.focus();
        //         contentDocument.execCommand("selectAll");
        //         EdtApi.sleep(20).then(() => {
        //             navigator.clipboard.writeText(msg).then(() => {
        //                 contentDocument.execCommand("paste");
        //                 resolve(true);
        //             }).catch(() => {
        //                 resolve(false);
        //             });
        //         });
        //     });
        // },
        getUserInfo() {
            try {
                let account = localStorage.getItem("mmkv.default\\SigninName")?.replace(/ /g, "");
                let avatarEl = document.querySelector('div.css-1dbjc4n.r-13awgt0>div.css-1dbjc4n.r-13awgt0 button[role="button"][tabindex="0"][aria-label]>div>div:nth-child(2)');
                let avatar = avatarEl?.style?.backgroundImage;
                if ('url("")' == avatar) avatar = "";
                if (avatar) avatar = avatar.replace('url("', "").replace('")', "");
                let nameEl = document.querySelector('div[data-text-as-pseudo-element]:not([aria-hidden="true"])');
                let userName = nameEl?.getAttribute("data-text-as-pseudo-element") || "";
                return {
                    avatar,
                    userName,
                    account,
                    toDataUrl: true
                };
            } catch (error) {
                return null;
            }
        }
    }
};